<!-- 会话管理页面 -->
<template>
  <view class="session-container">
    <!-- 筛选条件 -->
    <view class="filter-section">
      <uni-search-bar
        v-model="searchKeyword"
        placeholder="搜索会话"
        @confirm="handleSearch"
      />
      <uni-datetime-picker
        v-model="dateRange"
        type="daterange"
        @change="handleDateRangeChange"
      />
      <uni-data-select
        v-model="statusFilter"
        :localdata="statusOptions"
        @change="handleStatusChange"
      />
    </view>

    <!-- 会话列表 -->
    <view class="session-list">
      <uni-table>
        <uni-tr>
          <uni-th>会话ID</uni-th>
          <uni-th>用户</uni-th>
          <uni-th>客服</uni-th>
          <uni-th>状态</uni-th>
          <uni-th>开始时间</uni-th>
          <uni-th>结束时间</uni-th>
          <uni-th>满意度</uni-th>
          <uni-th>操作</uni-th>
        </uni-tr>
        <uni-tr v-for="session in sessionList" :key="session.sessionId">
          <uni-td>{{ session.sessionId }}</uni-td>
          <uni-td>{{ session.userId }}</uni-td>
          <uni-td>{{ session.serviceId || '-' }}</uni-td>
          <uni-td>
            <uni-tag :type="getStatusType(session.status)">
              {{ getStatusText(session.status) }}
            </uni-tag>
          </uni-td>
          <uni-td>{{ formatTime(session.startTime) }}</uni-td>
          <uni-td>{{ session.endTime ? formatTime(session.endTime) : '-' }}</uni-td>
          <uni-td>
            <uni-rate
              v-if="session.satisfactionScore"
              :value="session.satisfactionScore"
              readonly
              size="18"
            />
            <text v-else>-</text>
          </uni-td>
          <uni-td>
            <view class="operation-buttons">
              <button
                v-if="session.status === 'ACTIVE'"
                size="mini"
                type="warn"
                @click="handleEndSession(session)"
              >
                结束
              </button>
              <button
                size="mini"
                type="primary"
                @click="handleViewDetail(session)"
              >
                详情
              </button>
            </view>
          </uni-td>
        </uni-tr>
      </uni-table>

      <!-- 分页器 -->
      <uni-pagination
        :total="total"
        :pageSize="pageSize"
        :current="current"
        @change="handlePageChange"
      />
    </view>

    <!-- 会话详情弹窗 -->
    <uni-popup ref="detailPopup" type="dialog">
      <uni-popup-dialog
        mode="base"
        title="会话详情"
        :before-close="true"
        @close="handleCloseDetail"
      >
        <view class="session-detail" v-if="currentSession">
          <view class="detail-item">
            <text class="label">会话ID：</text>
            <text>{{ currentSession.sessionId }}</text>
          </view>
          <view class="detail-item">
            <text class="label">用户ID：</text>
            <text>{{ currentSession.userId }}</text>
          </view>
          <view class="detail-item">
            <text class="label">客服ID：</text>
            <text>{{ currentSession.serviceId || '-' }}</text>
          </view>
          <view class="detail-item">
            <text class="label">会话类型：</text>
            <text>{{ currentSession.sessionType }}</text>
          </view>
          <view class="detail-item">
            <text class="label">开始时间：</text>
            <text>{{ formatTime(currentSession.startTime) }}</text>
          </view>
          <view class="detail-item">
            <text class="label">结束时间：</text>
            <text>{{ currentSession.endTime ? formatTime(currentSession.endTime) : '-' }}</text>
          </view>
          <view class="detail-item">
            <text class="label">消息总数：</text>
            <text>{{ currentSession.messageCount || 0 }}</text>
          </view>
          <view class="detail-item">
            <text class="label">首次响应时间：</text>
            <text>{{ formatDuration(currentSession.avgResponseTime) }}</text>
          </view>
          <view class="detail-item">
            <text class="label">转接次数：</text>
            <text>{{ currentSession.transferCount || 0 }}</text>
          </view>
          <view class="detail-item">
            <text class="label">满意度评分：</text>
            <uni-rate
              v-if="currentSession.satisfactionScore"
              :value="currentSession.satisfactionScore"
              readonly
              size="18"
            />
            <text v-else>-</text>
          </view>
          <view class="detail-item">
            <text class="label">满意度评价：</text>
            <text>{{ currentSession.satisfactionComment || '-' }}</text>
          </view>
        </view>
      </uni-popup-dialog>
    </uni-popup>

    <!-- 结束会话弹窗 -->
    <uni-popup ref="endSessionPopup" type="dialog">
      <uni-popup-dialog
        mode="input"
        title="结束会话"
        placeholder="请输入结束原因"
        :before-close="true"
        @confirm="confirmEndSession"
        @close="handleCloseEndSession"
      />
    </uni-popup>
  </view>
</template>

<script>
import { ref, onMounted } from 'vue';
import { getSessionList, endSession, getSessionDetail } from '@/api/chatSession';

export default {
  name: 'SessionManagement',
  setup() {
    const searchKeyword = ref('');
    const dateRange = ref([]);
    const statusFilter = ref('');
    const sessionList = ref([]);
    const total = ref(0);
    const current = ref(1);
    const pageSize = ref(10);
    const currentSession = ref(null);
    const detailPopup = ref(null);
    const endSessionPopup = ref(null);
    const sessionToEnd = ref(null);

    const statusOptions = [
      { value: '', text: '全部状态' },
      { value: 'ACTIVE', text: '进行中' },
      { value: 'ENDED', text: '已结束' },
      { value: 'TRANSFERRED', text: '已转接' }
    ];

    // 加载会话列表
    const loadSessions = async () => {
      try {
        const res = await getSessionList({
          current: current.value,
          pageSize: pageSize.value,
          keyword: searchKeyword.value,
          status: statusFilter.value,
          startDate: dateRange.value[0],
          endDate: dateRange.value[1]
        });
        sessionList.value = res.data.records;
        total.value = res.data.total;
      } catch (error) {
        console.error('加载会话列表失败:', error);
        uni.showToast({
          title: '加载会话列表失败',
          icon: 'none'
        });
      }
    };

    // 格式化时间
    const formatTime = (time) => {
      if (!time) return '-';
      return new Date(time).toLocaleString();
    };

    // 格式化时长
    const formatDuration = (seconds) => {
      if (!seconds) return '0秒';
      if (seconds < 60) return seconds + '秒';
      const minutes = Math.floor(seconds / 60);
      if (minutes < 60) return minutes + '分钟';
      const hours = Math.floor(minutes / 60);
      const remainingMinutes = minutes % 60;
      return hours + '小时' + (remainingMinutes > 0 ? remainingMinutes + '分钟' : '');
    };

    // 获取状态类型
    const getStatusType = (status) => {
      switch (status) {
        case 'ACTIVE':
          return 'primary';
        case 'ENDED':
          return 'success';
        case 'TRANSFERRED':
          return 'warning';
        default:
          return 'default';
      }
    };

    // 获取状态文本
    const getStatusText = (status) => {
      switch (status) {
        case 'ACTIVE':
          return '进行中';
        case 'ENDED':
          return '已结束';
        case 'TRANSFERRED':
          return '已转接';
        default:
          return '未知';
      }
    };

    // 处理搜索
    const handleSearch = () => {
      current.value = 1;
      loadSessions();
    };

    // 处理日期范围变化
    const handleDateRangeChange = () => {
      current.value = 1;
      loadSessions();
    };

    // 处理状态筛选变化
    const handleStatusChange = () => {
      current.value = 1;
      loadSessions();
    };

    // 处理分页变化
    const handlePageChange = (e) => {
      current.value = e.current;
      loadSessions();
    };

    // 查看会话详情
    const handleViewDetail = async (session) => {
      try {
        const res = await getSessionDetail(session.sessionId);
        currentSession.value = res.data;
        detailPopup.value.open();
      } catch (error) {
        console.error('获取会话详情失败:', error);
        uni.showToast({
          title: '获取会话详情失败',
          icon: 'none'
        });
      }
    };

    // 关闭详情弹窗
    const handleCloseDetail = () => {
      currentSession.value = null;
      detailPopup.value.close();
    };

    // 结束会话
    const handleEndSession = (session) => {
      sessionToEnd.value = session;
      endSessionPopup.value.open();
    };

    // 确认结束会话
    const confirmEndSession = async (reason) => {
      if (!sessionToEnd.value) return;
      
      try {
        await endSession(sessionToEnd.value.sessionId, reason);
        uni.showToast({
          title: '会话已结束',
          icon: 'success'
        });
        loadSessions();
      } catch (error) {
        console.error('结束会话失败:', error);
        uni.showToast({
          title: '结束会话失败',
          icon: 'none'
        });
      } finally {
        handleCloseEndSession();
      }
    };

    // 关闭结束会话弹窗
    const handleCloseEndSession = () => {
      sessionToEnd.value = null;
      endSessionPopup.value.close();
    };

    onMounted(() => {
      // 设置默认时间范围为最近7天
      const end = new Date();
      const start = new Date();
      start.setDate(start.getDate() - 6);
      dateRange.value = [
        start.toISOString().split('T')[0],
        end.toISOString().split('T')[0]
      ];
      loadSessions();
    });

    return {
      searchKeyword,
      dateRange,
      statusFilter,
      statusOptions,
      sessionList,
      total,
      current,
      pageSize,
      currentSession,
      detailPopup,
      endSessionPopup,
      formatTime,
      formatDuration,
      getStatusType,
      getStatusText,
      handleSearch,
      handleDateRangeChange,
      handleStatusChange,
      handlePageChange,
      handleViewDetail,
      handleCloseDetail,
      handleEndSession,
      confirmEndSession,
      handleCloseEndSession
    };
  }
};
</script>

<style lang="scss">
.session-container {
  padding: 20rpx;

  .filter-section {
    display: flex;
    gap: 20rpx;
    margin-bottom: 20rpx;
    flex-wrap: wrap;
  }

  .session-list {
    .operation-buttons {
      display: flex;
      gap: 10rpx;
    }
  }

  .session-detail {
    padding: 20rpx;

    .detail-item {
      display: flex;
      margin: 10rpx 0;

      .label {
        width: 120rpx;
        color: #666;
      }
    }
  }
}
</style> 